<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>EasyRBAC-SSO</title>
    <script src="https://cdn.staticfile.org/jquery/1.7.2/jquery.min.js"></script>
    <script src="https://cdn.staticfile.org/particles.js/2.0.0/particles.min.js"></script>

    <style>
        body {
            margin: 0;
            font: normal 75% Arial, Helvetica, sans-serif;
        }
        
        canvas {
            display: block;
            vertical-align: bottom;
        }
        /* ---- particles.js container ---- */
        
        #particles-js {
            position: absolute;
            width: 100%;
            height: 100%;
            background-color: #A9ACAF;
            background-image: url("");
            background-repeat: no-repeat;
            background-size: cover;
            background-position: 50% 50%;
        }
        /* ---- stats.js ---- */
        
        .count-particles {
            background: #000022;
            position: absolute;
            top: 48px;
            left: 0;
            width: 80px;
            color: #13E8E9;
            font-size: .8em;
            text-align: left;
            text-indent: 4px;
            line-height: 14px;
            padding-bottom: 2px;
            font-family: Helvetica, Arial, sans-serif;
            font-weight: bold;
        }
        
        .labels {
            width: 90px;
            background: rgba(145, 135, 135, 0.26);
            display: inline-block;
            text-align: right;
            padding-right: 10px;
            border-radius: 4px;
            color: #222;
        }
        
        .user-input {
            border: 0;
            background: transparent;
            border-bottom: 1px solid #999;
            outline: none;
            width: 220px;
            padding-left: 10px;
        }
        
        .js-count-particles {
            font-size: 1.1em;
        }
        
        #stats,
        .count-particles {
            -webkit-user-select: none;
        }
        
        #stats {
            border-radius: 3px 3px 0 0;
            overflow: hidden;
        }
        
        .count-particles {
            border-radius: 0 0 3px 3px;
        }
        
        .panel {
            font-family: "Source Sans Pro";
            font-size: 1.3em;
            position: absolute;
            width: 400px;
            top: 50%;
            left: 50%;
            box-sizing: border-box;
            z-index: 100;
            height: 200px;
            transform: translate(-50%, -50%);
            padding: 20px;
            border-radius: 4px;
            margin: 0;
            background: rgba(238, 238, 238, 0.82);
        }
        
        h1 {
            display: block;
            font-size: 1em;
            -webkit-margin-before: 0.67em;
            -webkit-margin-after: 0.67em;
            -webkit-margin-start: 0px;
            -webkit-margin-end: 0px;
            font-weight: bold;
            margin: 0px 0px;
            text-align: center;
            border-bottom: 1px solid #999;
            padding: 10px;
        }
        
        .button-group {
            padding: 10px;
        }
        
        button {
            background: #2196F3;
            border: 0;
            padding: 10px;
            width: 75px;
            border-radius: 5px;
            cursor: pointer;
            float: right;
        }
        
        button:hover {
            background: #0e64a8;
        }
        
        .password-show {
            padding: 0px 10px 10px 10px;
            border-bottom: 1px solid #999;
        }
    </style>
</head>

<body>
    <div id="particles-js">
        <div class="panel">
            <h1>EasyRBAC Login</h1>
            <div style="padding: 10px;">
                <span class="labels">User Name</span>
                <input type="text" id="userName" class="user-input">
            </div>
            <div class="password-show">
                <span class="labels">Password</span>
                <input type="text" id="pwd" class="user-input">
                <span class="msg"></span>
            </div>
            <div class="button-group">
                <button onclick="login()">login</button>
                <button style="margin-right: 10px;">logout</button>
            </div>
        </div>
        <canvas class="particles-js-canvas-el" width="1192" height="833" style="width: 100%; height: 100%;"></canvas>
    </div>
    <script>
        particlesJS("particles-js", {
            "particles": {
                "number": {
                    "value": 80,
                    "density": {
                        "enable": true,
                        "value_area": 800
                    }
                },
                "color": {
                    "value": "#ffffff"
                },
                "shape": {
                    "type": "circle",
                    "stroke": {
                        "width": 0,
                        "color": "#000000"
                    },
                    "polygon": {
                        "nb_sides": 5
                    },
                    "image": {
                        "src": "img/github.svg",
                        "width": 100,
                        "height": 100
                    }
                },
                "opacity": {
                    "value": 0.5,
                    "random": false,
                    "anim": {
                        "enable": false,
                        "speed": 1,
                        "opacity_min": 0.1,
                        "sync": false
                    }
                },
                "size": {
                    "value": 3,
                    "random": true,
                    "anim": {
                        "enable": false,
                        "speed": 40,
                        "size_min": 0.1,
                        "sync": false
                    }
                },
                "line_linked": {
                    "enable": true,
                    "distance": 150,
                    "color": "#ffffff",
                    "opacity": 0.4,
                    "width": 1
                },
                "move": {
                    "enable": true,
                    "speed": 6,
                    "direction": "none",
                    "random": false,
                    "straight": false,
                    "out_mode": "out",
                    "bounce": false,
                    "attract": {
                        "enable": false,
                        "rotateX": 600,
                        "rotateY": 1200
                    }
                }
            },
            "interactivity": {
                "detect_on": "canvas",
                "events": {
                    "onhover": {
                        "enable": true,
                        "mode": "grab"
                    },
                    "onclick": {
                        "enable": true,
                        "mode": "push"
                    },
                    "resize": true
                },
                "modes": {
                    "grab": {
                        "distance": 140,
                        "line_linked": {
                            "opacity": 1
                        }
                    },
                    "bubble": {
                        "distance": 400,
                        "size": 40,
                        "duration": 2,
                        "opacity": 8,
                        "speed": 3
                    },
                    "repulse": {
                        "distance": 200,
                        "duration": 0.4
                    },
                    "push": {
                        "particles_nb": 4
                    },
                    "remove": {
                        "particles_nb": 2
                    }
                }
            },
            "retina_detect": true
        });

        const ssoApiBaseUrl = "http://easyrbac.uliian.com/sso/UserLogin"

        let existResult = getTokenInfo();

        if (existResult !== null) {
            login();
        }

        async function login() {
            let appCode = getParameterByName("appCode");
            let env = getParameterByName("env")
            let tokenResult = getTokenInfo();
            if (tokenResult == null) {
                tokenResult = await getToken()
                if (tokenResult == null || tokenResult == undefined) {
                    return
                }
            }

            fetch(`${ssoApiBaseUrl}/callbackUrl?appCode=${appCode}&env=${env}`).then(response => {
                if (response.ok) {
                    response.json().then(appCallbackUrl => {
                        debugger;
                        if (appCallbackUrl.callbackType === 1) {
                            let callBackurl = `${appCallbackUrl.callbackUrl}?token=${tokenResult.token}&callback=?`
                            $.getJSON(callBackurl).then(rep => {
                                if (rep.success) {
                                    //window.location.href = "http://localhost:8010"
                                    let fromUrl = getParameterByName("from");
                                    console.log(fromUrl)
                                    if (fromUrl != null) {
                                        window.location.href = fromUrl;
                                    }
                                } else {
                                    document.querySelector(".msg").innerHTML = "登录失败，请联系管理员"
                                }
                            })
                        } else if (appCallbackUrl.callbackType === 4) {
                            window.location.href = `${appCallbackUrl.callbackUrl}?token=${tokenResult.token}`
                        }

                    })
                } else {
                    document.querySelector(".msg").innerHTML = "APPCode错误"
                }
            })
        }

        function getParameterByName(name, url) {
            if (!url) url = window.location.href;
            name = name.replace(/[\[\]]/g, "\\$&");
            var regex = new RegExp("[?&]" + name + "(=([^&]*)|&|$)"),
                results = regex.exec(url);
            if (!results) return null;
            if (!results[2]) return '';
            return decodeURIComponent(results[2].replace(/\+/g, " "));
        }

        function saveTokenInfo(loginResult) {
            debugger;
            let expireIn = loginResult.expireIn;
            let now = new Date().valueOf();
            let expireOn = now + expireIn * 1000;
            let tokenObj = JSON.stringify({
                token: loginResult.token,
                expireOn: expireOn
            });
            localStorage.setItem("token", tokenObj);
        }

        function getTokenInfo() {
            let tokenJson = localStorage.getItem("token");
            if (tokenJson == null) {
                return null;
            }
            tokenResult = JSON.parse(tokenJson);
            if (tokenResult.expireOn > new Date().valueOf()) {
                return tokenResult;
            } else {
                debugger;
                localStorage.removeItem("token")
            }
            return null;
        }

        async function getToken() {
            let loginUrl = ssoApiBaseUrl;
            let userName = document.getElementById("userName").value;
            let password = document.getElementById("pwd").value;
            let appCode = "easyRBAC";

            let response = await fetch(loginUrl, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json"
                },
                model: "cors",
                body: JSON.stringify({
                    userName,
                    password,
                    appCode
                }),
            })

            let result = await response.json()
            if (response.ok) {
                document.querySelector(".msg").innerHTML = "登录成功，等待验证"
                debugger;
                saveTokenInfo(result);
                return result;
            } else {
                alert(result.message)
            }
        }
    </script>
</body>

</html>